<template>
  <label class="ui-switch" :class="['ui-switch--' + size, {'is-disabled': disabled}]">
    <div class="ui-switch__main">
      <el-switch class="ui-switch__input" :width="switchWidth" :disabled="disabled" v-model="innerValue"></el-switch>
      <span class="ui-switch__label">
        <slot>
          <template v-if="trueLabel && falseLabel">{{ value ? trueLabel : falseLabel }}</template>
        </slot>
      </span>
    </div>
  </label>
</template>
<script>
import ElSwitch from 'element-ui/lib/switch'
import 'element-ui/lib/theme-chalk/switch.css'

export default {
  name: 'UiSwitch',
  components: {
    ElSwitch
  },
  props: {
    value: {
      type: [Boolean, Number]
    },
    size: {
      type: String,
      default: 'small',
      validator (value) {
        return ['small', 'mini'].includes(value)
      }
    },
    disabled: {
      type: Boolean
    },
    trueLabel: {
      type: String
    },
    falseLabel: {
      type: String
    }
  },
  computed: {
    innerValue: {
      get () {
        if (typeof this.value === 'number') {
          return this.value === 1
        }
        return this.value
      },
      set (val) {
        if (typeof this.value === 'number') {
          this.$emit('input', val ? 1 : 0)
        } else {
          this.$emit('input', val)
        }
      }
    },
    switchWidth () {
      const sizeMap = {
        small: 40,
        mini: 28
      }
      return sizeMap[this.size]
    }
  }
}
</script>
<style lang="less">
.ui-switch{
  display: inline-block;
  vertical-align: top;
  padding-top: 6px;
  padding-bottom: 6px;
  &.is-disabled{
    color: #aaa;
    cursor: not-allowed;
  }
}
.ui-switch__main{
  display: flex;
  flex-direction: row;
  align-items: center;
  line-height: 1;
}
.ui-switch__label{
  margin-left: 6px;
}
.ui-switch--mini{
  .el-switch__core{
    height: 16px;
    &:after {
      width: 12px;
      height: 12px;
    }
  }
  .el-switch.is-checked {
    .el-switch__core::after{
      margin-left: -13px;
    }
  }
}
</style>
